package model;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

import resources.TestImages;

import view.View;
import control.Control;

public class Model {
	
	private static Model model=new Model();
	private Control control;
	private View view;
	private MutableTreeNode tree=new DefaultMutableTreeNode("MP3's");
	private final MP3Node DEFAULT_MP3NODE=new MP3Node("",new MP3TagData("","","","",TestImages.jpeg));
	private MP3Node curMP3=DEFAULT_MP3NODE;
	
	
	private Model(){
		
	}
	
	public void init(){
		control=Control.getControl();
		view=View.getView();
		loadFileTree();
	}
	
	//should load all mp3 tags, and combines them into a tree consisting of DirectoryNodes 
	//and MP3Nodes
	private void loadFileTree(){
		//TODO implement File loading and tree generation
		
		//testing purpose
		for (int k=0;k<10;k++){
			DirectoryNode interpret = new DirectoryNode("interpretenVZ:"+k);
			((DefaultMutableTreeNode) tree).add(interpret);
			for (int j=0;j<10;j++){
				DirectoryNode album = new DirectoryNode(j+". AlbumVZ");
				interpret.add(album);
				for (int i=0;i<10;i++){
					album.add(new MP3Node("Song_"+i+".mp3",new MP3TagData("album nr.:"+j,"2011","interpret nr.:"+k,"Song Nr.:" +i, TestImages.jpeg )));
				}
			}
		}
	}
	
	
	public static Model getModel(){
		return model;
	}
	
	public MutableTreeNode getFileTree(){
		return tree;
	}
	
	public String getCurrentYear(){
		return curMP3.getMP3TagData().getYear();
	}
	
	public String getCurrentInterpret(){
		return curMP3.getMP3TagData().getInterpret();
	}
	public String getCurrentAlbum(){
		return curMP3.getMP3TagData().getAlbum();
	}
	public String getCurrentSongTitle(){
		return curMP3.getMP3TagData().getSongTitle();
	}
	public byte[] getCurrentFrontCover(){
		return curMP3.getMP3TagData().getFrontCover();
	}
	
	public void selectNewCurrentMP3(MP3Node node){
		
		curMP3=node;
		view.update();
	}
	
	//will be used in milestone 2
	private void saveMP3TagData(MP3TagData Data){
		//TODO implement save routine
	}
	
	//edits if necessary the mp3tagdata associated with the current mp3node
	//and initiates save routine no action is performed if the data from the view
	//is the same as the local data
	public void editCurMP3TagData(){
		if (curMP3!=DEFAULT_MP3NODE){
			MP3TagData newData=new MP3TagData(view.getAlbum(),view.getYear(),view.getInterpret(),view.getSongTitle(),curMP3.getMP3TagData().getFrontCover());
			if (!newData.equals(curMP3.getMP3TagData())){
				curMP3.setMP3TagData(newData);			
				saveMP3TagData(newData);
			}
		}
	}
}
